package utils;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class RuntimeUtil {


    public static String exec(String command) {
        StringBuilder sb = new StringBuilder();
        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            process.getOutputStream().close();
            reader.close();
            process.destroy();
        } catch (Exception e) {
            System.out.println("执行外部命令错误，命令行:" + command+e);
        }
        return sb.toString();
    }

    private static String jps() {
        return exec("jps -l");
    }
    private static String getPid(){
        String name = ManagementFactory.getRuntimeMXBean().getName();
        System.out.println(name);
        return name.split("@")[0];
    }


    public static void restartApp(){
        long period = 1500;
        long initialDelay = 1000;
        String jpsPre = RuntimeUtil.jps();
        System.out.println(jpsPre);
        ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
                new BasicThreadFactory.Builder().namingPattern("example-schedule-pool-%d").daemon(true).build());
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!jpsPre.equals(RuntimeUtil.jps())){
                    System.out.println("关闭程序");
                    System.exit(0);
                }
            }
        },initialDelay,period, TimeUnit.MILLISECONDS);
        String restartBat = CommonUtil.getFilePath()+ File.separator+"restart.bat";
        String strcmd = "cmd /c start  "+restartBat;
        RuntimeUtil.exec(strcmd);
    }



}